package com.mall.sun.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.mall.sun.model.po.Permission;
import com.mall.sun.model.po.User;
import com.mall.sun.model.vo.ResultVO;
import com.mall.sun.repository.mapper.UserRoleMapper;
import com.mall.sun.service.UserService;
import com.mall.sun.utils.CommonUtil;
import com.mall.sun.utils.MD5Util;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 * description:  <br>
 * date: 2021/8/24 12:42 <br>
 * author: ztz <br>
 * version: 1.0 <br>
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/register")
    public ResultVO register(@RequestBody User user){
        User name = null;
        try {
            name = userService.getOne(new QueryWrapper<User>().eq("user_name", user.getUserName()));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        if (name!=null) {
            return new ResultVO("注册失败",400,"用户名存在");
        }else {
            user.setPassword(MD5Util.encode(user.getPassword()));
            return CommonUtil.ajaxReturn(userService.register(user));
        }
    }

    @GetMapping("/perms/{username}")
    public ResultVO getPerms(@PathVariable String username){
        if(userService.getOne(new QueryWrapper<User>().eq("user_name",username))==null) {
            return new ResultVO("查询失败",400,"所查询用户不存在");
        }
        List<Permission> permissions = userService.findPermissionByUsername(username);
        ArrayList<String[]> list = new ArrayList<>();
        for (Permission permission : permissions) {
            String[] strings = new String[1];
            strings[0]=permission.getPermTag();
            list.add(strings);
        }
        return CommonUtil.ajaxReturn(list);
    }

    @GetMapping("/count")
    public ResultVO userMapCount(){
        return CommonUtil.ajaxReturn(userService.userMapCount());
    }
}
